<?php


namespace App\Http\Controllers\Backend;

use App\Businesses\BusinessState;
use App\Http\Requests\Company\ActivityRequest;
use App\Services\Base\Interfaces\ConfigServiceInterface;
use App\Services\Business\Interfaces\ActivityServiceInterface;
use App\Services\Business\Models\Decorate;
use App\Services\Business\Services\ActivityService;
use App\Services\Business\Interfaces\CommentServiceInterface;
use App\Services\Business\Interfaces\VideoServiceInterface;
use App\Services\Business\Models\MediaImage;
use App\Services\Business\Services\CommentService;
use App\Services\Member\Interfaces\UserServiceInterface;
use App\Services\Member\Models\Activity;
use App\Services\Member\Models\User;
use App\Services\Member\Services\UserService;
use App\Zesow\WechatMini;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class ActivityController extends BaseController
{


    /**
     * @var CommentService
     */
    protected $commentService;
    /**
     * @var UserService
     */
    protected $userService;
    protected $businessState;

    /**
     * @var ActivityService
     */
    protected $activityService;


    public function __construct(

        CommentServiceInterface  $commentService,
        UserServiceInterface     $userService,
        BusinessState            $businessState,
        ActivityServiceInterface $activityService

    )
    {

        $this->commentService = $commentService;
        $this->userService = $userService;
        $this->businessState = $businessState;
        $this->activityService = $activityService;

    }

    public function index(Request $request)
    {

        $companyId = $this->loginCompanyId();
        $size = $request->input('size', 10);
        $processId = $request->input('process_id');
        $userId = $request->input('user_id');
        $decorateId = $request->input('decorate_id');
        $status = $request->input('status');
        $activities = Activity::query()
            ->with(['images', 'videos', 'process'])
            ->when($userId, function ($query) use ($userId) {
                $query->where('user_id', $userId);
            })
            ->when($decorateId, function ($query) use ($decorateId) {
                $query->where('decorate_id', $decorateId);
            })
            ->when($status, function ($query) use ($status) {
                $query->whereIn('status', $status);

            })
            ->when($processId, function ($query) use ($processId) {
                $query->where('process_id', $processId);
            })
            ->where('company_id', $companyId)
            ->orderBy('created_at', 'DESC')
            ->paginate($size);
        //客户
        $customers = User::query()
            ->whereIn('id', array_unique(array_column($activities->items(), 'customer_id')))
            ->select(['id', 'nick_name', 'avatar', 'mobile'])
            ->get()
            ->keyBy('id');

        $decorates = Decorate::query()
            ->whereIn('id', array_unique(array_column($activities->items(), 'decorate_id')))
            ->select(['id', 'remark_name', 'district', 'created_at'])
            ->get()
            ->keyBy('id');
        //发布的人
        $user = User::query()
            ->whereIn('id', array_column($activities->items(), 'user_id'))
            ->select(['id', 'nick_name', 'avatar', 'mobile'])
            ->get()
            ->keyBy('id');
        return $this->successData(compact('activities', 'customers', 'user', 'decorates'));

    }


    /**
     * 获取最新发表的动态用的客户
     * @param Request $request
     * @return JsonResponse
     */
    public function latest(Request $request)
    {
        $companyId = $this->loginCompanyId();
        $userId = $this->id();
        $decorateId = $request->input('decorate_id');
        $activity = Activity::query()
            ->with(['process:id,title', 'customer:id,nick_name,avatar'])
            ->when($decorateId, function ($query) use ($decorateId) {
                $query->where('decorate_id', $decorateId);
            })
            ->where('company_id', $companyId)
            ->where('user_id', $userId)
            ->latest()
            ->first();
        if ($activity) {
            $customer = $activity->customer;
            $process = $activity->process;
            $decorate = $activity->decorate;
        } else {
            $decorate = Decorate::query()
                ->when($decorateId, function ($query) use ($decorateId) {
                    $query->where('id', $decorateId);
                })
                ->where('company_id', $companyId)
                ->latest()
                ->first();
            $customer = $decorate->customer()->select(['id', 'nick_name', 'avatar'])->first();
            $process = $decorate->processes()->first();

        }
        return $this->successData(compact('customer', 'process', 'decorate'));

    }


    /**
     * 动态详情
     * @param $id
     * @return JsonResponse
     */
    public
    function detail($id)
    {
        $activity = Activity::query()
            ->with(['user', 'customer', 'images', 'videos'])
            ->where('id', $id)->first();

        return $this->successData(compact('activity'));

    }

    /**
     * 新增一条动态
     * @param ActivityRequest $request
     * @param Activity $appraise
     * @return JsonResponse
     */
    public
    function store(ActivityRequest $request, Activity $activity)
    {


        $data = $request->filldata();
        DB::transaction(function () use ($activity, $data) {

            $activity->fill($data)->save($data);
            $data['image_ids'] && $activity->images()->attach($data['image_ids']);
            $data['video_ids'] && $activity->videos()->attach($data['video_ids']);

        });
        return $this->success(__('新增动态成功'));
    }


    /**
     * 更新动态
     * @param ActivityRequest $request
     * @param $id
     * @return JsonResponse
     */
    public
    function update(ActivityRequest $request, $id)
    {

        $activity = Activity::query()->where('id', $id)->first();
        $data = $request->filldata();
        DB::transaction(function () use ($activity, $data) {
            $activity->fill($data)->save();
            $activity->images()->sync($data['image_ids']);
            $activity->videos()->sync($data['video_ids']);

        });

        return $this->success(__('更新成功'));

    }

    /**
     *动态删除
     * @param $id
     * @param ConfigServiceInterface $configService
     * @param VideoServiceInterface $videoService
     * @return JsonResponse
     */
    public
    function delete($id, ConfigServiceInterface $configService, VideoServiceInterface $videoService)
    {
        $activity = Activity::query()->where('id', $id)->first();

        DB::transaction(function () use ($activity, $videoService, $configService) {

            //删除视频点播的图片
            if ($activity->images->isNotEmpty()) {
                $activity->images()->delete();
                $videoService->deleteImage(implode(',', $activity->images->pluck('media_id')->toArray()), $configService);
            }

            //删除阿里云的视频
            if ($activity->videos->isNotEmpty()) {
                $activity->videos()->delete();
                $videoService->deleteVideo(implode(',', $activity->videos->pluck('aliyun_video_id')->toArray()), $configService);
            }
            //删除动态本身
            $activity->delete();
        });

        return $this->success(__('动态删除成功'));
    }

    /**
     * 动态验收
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public
    function verify(Request $request, $id)
    {

        $remark = $request->input('remark');
        $status = $request->input('status');
        if (!$remark || $status) {
            $this->error(__('参数错误'));
        }
        $activity = Activity::query()->where('id', $id)->first();
        $activity->update(['remark' => $remark, 'status' => $status]);
        return $this->success(__('更新成功'));
    }

    public function checkImage(Request $request)
    {

        $file = $request->file('file');
        $app = WechatMini::getInstance();
        $data = $app->content_security->checkImage($file);
        if ($data['errcode'] == "87014") {
            return $this->error(__('请检查图片是否存在敏感内容,重新上传'));
        }
        return $this->success(__('成功'));
    }

    public function upload(Request $request)
    {
        $file = $request->file('file');
        $prefix = 'test/' . date("Ymd");
        $data =  save_image($file, $prefix);
        $image =  MediaImage::create([
            'title' => $data['name'],
            'url' => $data['urlMedium'],
            'url_small'=>$data['urlSmall'],
            'user_id'=>Auth::id(),
            'company_id' =>$this->loginCompanyId(),

        ]);
        return $this->successData(compact('image'));


    }

}
